<style lang="less" scoped>
@mbox: 980px;
.point-card {
  width: 300px;
  height: 185;
  box-shadow: 0px 0px 20px #d8d8d8;
  margin: 10px;
  border-radius: 8.8px;
  padding: 10px;
  position: relative;
  float: left;
  cursor: pointer;
  .p-b {
    text-align: center;
    font-size: 70px;
  }
  .p-c {
    font-size: 20px;
    width: 50%;
    float: left;
  }
  .c-r {
    text-align: right;
  }
}
.point-card-x {
  box-shadow: 0px 0px 20px #57a3f3;
}
.h-box {
  height: 41px;
  background: #fff;
  box-shadow: 0px 2px 1px #e6e6e6;
  &-head {
    height: 41px;
  }
  .h-logo {
    width: 104px;
    font-size: 26px;
    float: left;
  }
  .navbox{
    width: 620px;
    height: 41px;
    float: left;
  }
  .infobox{
    width: 256px;
    height: 41px;
    float: right;
    text-align: right;
    line-height: 41px;
  }
}
.box-center {
  width: @mbox;
  margin: 0 auto;
}
</style>

<template>
  <Layout class="main">
    <div class="h-box">
      <div class="box-center h-box-head">
        <div class="h-logo">
          天亿软件
        </div>
        <div class="navbox">
          <div class="tag-nav-wrapper">
            <tags-nav :value="$route"
                  @input="handleClick"
                  :list="tagNavList"
                  @on-close="handleCloseTag" />
          </div>
        </div>
        <div class="infobox">
          <Button v-if="JSON.stringify(userInfo) !== '{}' && userInfo.role_id === 1" @click="renew" type="text">购买点卡</Button>
          <Button v-if="JSON.stringify(userInfo) === '{}'" type="text" @click="showModal">登录</Button>
          <Button v-if="JSON.stringify(userInfo) === '{}'" type="text" @click="showModalRegister">注册</Button>
          <span style="text-align: center;" v-if="JSON.stringify(userInfo) !== '{}'">
            <Dropdown @on-click="grchange">
              <a href="javascript:void(0)">
                {{userInfo.name}}
                <Icon type="ios-arrow-down"></Icon>
              </a>
              <DropdownMenu slot="list">
                <DropdownItem name="ddjl">订单记录</DropdownItem>
                <DropdownItem name="tcdl">退出登录</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </span>
          <Avatar icon="ios-person" />
        </div>
      </div>
    </div>
    <div class="box-center">
      <div style="margin-top: 20px;">
        <keep-alive :include="cacheList">
          <router-view/>
        </keep-alive>
      </div>
    </div>
    <login-form @on-success-valid="loginHandleSubmit"
                @on-modal-valid="modalValidL"
                v-bind:modalRegister="modalVisible"></login-form>
    <register-form @on-success-valid="handleSubmit"
                   @on-modal-valid="modalValidR"
                   v-bind:modalRegister="modalRegister"></register-form>
    <Modal v-model="renewModal"
           width="672px"
           title="购买点卡">
      <div style="overflow:hidden;">
        <div v-for="(item, index) in kplist"
            :key="index"
            :class="item.renewModal === true ? 'point-card point-card-x' : 'point-card'"
            @click="single(index)">
          <div class="p-b">{{item.name}}</div>
          <div class="p-c">有效期:{{item.days}}天</div>
          <div class="p-c c-r">价格:{{item.price}}元</div>
          <Radio style="position: absolute;top: 8px;left:8px;"
                v-model="item.renewModal"></Radio>
        </div>
      </div>
      <div slot="footer">
        <Button @click="paymentClose">关闭</Button>
        <Button type="primary"
                size="large"
                @click="payment"
                :disabled="disabled">下单</Button>
      </div>
    </Modal>
    <Modal v-model="zfmodal"
           width="360"
           :mask-closable="false">
      <p slot="header"
         style="color:#57a3f3;text-align:center">
        <Icon type="ios-clipboard" />
        <span>下单成功 - 请使用支付宝扫码支付</span>
      </p>
      <div style="text-align:center">
        <Alert type="warning">提醒：扫码后请将下方的6位数字填写到支付宝转账的备注，请务必转账正确的金额（如月卡金额，天卡金额），否则都将无法自动到账</Alert>
        <p style="font-size: 18px;margin-bottom: 9px;">请在
          <span style="color: #ed4014;">支付宝备注栏</span>
            输入：
          <span style="color: #ff9900;font-size: 32px;">{{dindan.order_id}}</span>
        </p>
        <qrcode-vue :value="AliPay.pay_r_code_url"
                    size="200"
                    level="H"></qrcode-vue>
      </div>
      <div slot="footer">
        <Button type="info"
                size="large"
                long
                @click="wczf">完成支付</Button>
      </div>
    </Modal>
  </Layout>
</template>
<script>
import LoginForm from '_c/login-form'
import RegisterForm from '_c/register-form'
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import Fullscreen from './components/fullscreen'
import Language from './components/language'
import { mapMutations, mapActions } from 'vuex'
import { getNewTagList, getNextName } from '@/libs/util'
import minLogo from '@/assets/images/logo-min.jpg'
import maxLogo from '@/assets/images/logo.jpg'
import './main.less'
import QrcodeVue from 'qrcode.vue'
export default {
  name: 'Main',
  components: {
    QrcodeVue,
    RegisterForm,
    LoginForm,
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    User
  },
  data () {
    return {
      kplist: [],
      AliPay: {
        pay_r_code_url: '',
        secret: '',
        sid: ''
      },
      cardExpire: '',
      dindan: {},
      thisindex: 0,
      zfmodal: false,
      disabled: true,
      renewModal: false,
      userInfo: {},
      collapsed: false,
      minLogo,
      maxLogo,
      isFullscreen: false,
      modalVisible: false,
      modalRegister: false,
      options: {
        trigger: '.ivu-modal-header',
        body: '.ivu-modal',
        recover: true
      }
    }
  },
  computed: {
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvator () {
      return this.$store.state.user.avatorImgPath
    },
    cacheList () {
      return this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []
    },
    menuList () {
      return this.$store.getters.menuList
    },
    local () {
      return this.$store.state.app.local
    }
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal'
    ]),
    ...mapActions([
      'handleLogin',
      'getUserInfo'
    ]),
    getCards () {
      let data = {
        limit: '0,10'
      }
      this.$api.repeater(this, 'getCards', data).then(res => {
        this.renewModal = true
        for (let i = 0, len = res.msg.records.length; i < len; i++) {
          this.kplist[i] = {}
          this.kplist[i] = {
            ...res.msg.records[i],
            renewModal: false
          }
        }
      })
    },
    grchange (e) {
      console.log(e)
      if (e === 'tcdl') this.logoff()
      if (e === 'ddjl') this.$router.push({name: 'level_2_3'})
    },
    getCardExpire () {
      this.$api.repeater(this, 'getCardExpire').then(res => {
        if (res.code === 1) {
          this.cardExpire = res.msg
          sessionStorage.cardExpire = JSON.stringify(res.msg)
        } else {
          this.cardExpire = res.msg
        }
      })
    },
    wczf () {
      this.zfmodal = false
      this.renewModal = false
    },
    single (i) {
      this.thisindex = 0
      this.disabled = true
      this.kplist[i].renewModal = !this.kplist[i].renewModal
      for (let j = 0; j < this.kplist.length; j++) {
        if (this.kplist[j].renewModal === true) {
          this.thisindex = this.kplist[j].id
          this.disabled = false
        }
        if (i !== j) this.kplist[j].renewModal = false
      }
    },
    payment () {
      let _this = this
      let data = {
        gid: 1,
        card_id: this.thisindex
      }
      this.$api.repeater(this, 'buyCard', data).then(res => {
        if (res.code === 1) {
          this.dindan = res.msg
          _this.$api.repeater(_this, 'getAliPay').then(res2 => {
            _this.zfmodal = true
            if (res2.code === 1) {
              _this.AliPay = res2.msg
            } else {
              _this.$Notice.error({
                title: res2.msg
              })
            }
          })
        } else {
          this.$Notice.error({
            title: res.msg
          })
        }
      })
    },
    paymentClose () {
      this.renewModal = false
    },
    logoff () {
      this.userInfo = {}
      sessionStorage.clear()
      this.$store.commit('setAccess', [])
    },
    setAccess (access) {
      this.$store.commit('setAccess', access)
      sessionStorage.access = JSON.stringify(access)
    },
    loginHandleSubmit (res) {
      this.userInfo = res.msg.user
      sessionStorage.userInfoDtat = JSON.stringify(res.msg.user)
      sessionStorage.token = res.msg.token
      if (res.msg.user.role_id === 1) {
        this.setAccess(['vip'])
        // this.getCardExpire()
      } else if (res.msg.user.role_id === 3) {
        this.setAccess(['admin'])
      }
    },
    renew () {
      this.getCards()
    },
    handleSubmit (res) {
      console.log(res)
    },
    showModal () {
      this.modalVisible = true
    },
    showModalRegister () {
      this.modalRegister = true
    },
    modalValidL (value) {
      this.modalVisible = value
    },
    modalValidR (value) {
      this.modalRegister = value
    },
    turnToPage (name) {
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name: name
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, name) {
      const nextName = getNextName(this.tagNavList, name)
      this.setTagNavList(res)
      if (type === 'all') this.turnToPage('home')
      else if (this.$route.name === name) this.$router.push({ name: nextName })
    },
    handleClick (item) {
      this.turnToPage(item.name)
    }
  },
  watch: {
    '$route' (newRoute) {
      this.setBreadCrumb(newRoute.matched)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
    }
  },
  mounted () {
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList()
    this.addTag(this.$store.state.app.homeRoute)
    this.setBreadCrumb(this.$route.matched)
    // 设置初始语言
    this.setLocal(this.$i18n.locale)

    // 文档提示
    // this.$Notice.info({
    //   title: '想快速上手，去看文档吧',
    //   duration: 0,
    //   render: (h) => {
    //     return h('p', {
    //       style: {
    //         fontSize: '13px'
    //       }
    //     }, [
    //       '点击',
    //       h('a', {
    //         attrs: {
    //           href: 'https://lison16.github.io/iview-admin-doc/#/',
    //           target: '_blank'
    //         }
    //       }, 'iview-admin2.0文档'),
    //       '快速查看'
    //     ])
    //   }
    // })
    if (sessionStorage.userInfoDtat !== undefined) {
      this.userInfo = JSON.parse(sessionStorage.userInfoDtat)
      this.$store.commit('setAccess', JSON.parse(sessionStorage.access))
    }
  }
}
</script>
